import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/order_list.dart';
import 'package:fsharing/core/viewmodels/pages/mine/order/order_confirm_receipt_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/order/order_delete_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/order/order_list_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/order/order_repay_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/pages/mine/order/order_detail_page.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/// 订单列表，storeId != null 表示是店铺订单
class OrderListPage extends StatelessWidget {
  final int storeId;
  final int index;

  OrderListPage({
    Key key,
    @required this.storeId,
    @required this.index,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => OrderListModel(Provider.of(context, listen: false), storeId, index),
        ),
        ChangeNotifierProvider(
          create: (context) => OrderRepayModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => OrderConfirmReceiptModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => OrderDeleteModel(Provider.of(context, listen: false)),
        )
      ],
      child: Consumer<OrderListModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget(
                list: model.list,
                orderList: model.orderList,
              );
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();
  final List<Order> list;
  final OrderList orderList;

  _SuccessWidget({
    Key key,
    @required this.list,
    @required this.orderList,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      child: ListView.separated(
        itemBuilder: (context, index) {
          Order order = list[index];
          return _OrderItemWidget(
            order: order,
          );
        },
        separatorBuilder: (context, index) {
          return Divider(
            height: 12,
            color: Colors.transparent,
          );
        },
        itemCount: list.length,
      ),
      enablePullDown: false,
      enablePullUp: !orderList.model.last,
      onLoading: () => _loadData(context),
    );
  }

  void _loadData(BuildContext context) async {
    OrderListModel orderListModel = Provider.of(context, listen: false);
    await orderListModel.loadData();
    _refreshController.loadComplete();
  }
}

class _OrderItemWidget extends StatelessWidget {
  final Order order;

  const _OrderItemWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        _OrderHeaderWidget(
          order: order,
        ),
        Theme(
          data: lightTheme(),
          child: Material(
            borderRadius: BorderRadius.vertical(
              bottom: Radius.circular(8),
            ),
            child: InkWell(
              child: Column(
                children: <Widget>[
                  _ProductListWidget(
                    list: order.orderDetails,
                  ),
                  _OrderBottomWidget(
                    order: order,
                  ),
                ],
              ),
              onTap: () {
                _onItemClicked(context);
              },
            ),
          ),
        ),
      ],
    );
  }

  void _onItemClicked(BuildContext context) {
    OrderListModel model = Provider.of(context, listen: false);
    Navigator.of(context).pushNamed(
      '/order/detail',
      arguments: OrderDetailPageArgs(model.storeId, order.code),
    );
  }
}

class _OrderHeaderWidget extends StatelessWidget {
  final Order order;

  const _OrderHeaderWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    bool showDiversion = order.referStoreId != null && order.referStoreId != order.storeId;
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/cart/img_store.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 45,
      child: Text(
        '订单编号：${order.code}' + (showDiversion ? '(导流)' : ''),
        style: TextStyle(color: showDiversion ? Theme.of(context).accentColor : Colors.white),
      ),
    );
  }
}

class _ProductListWidget extends StatelessWidget {
  final List<Product> list;

  const _ProductListWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemBuilder: (context, index) {
        return _ProductItemWidget(
          product: list[index],
        );
      },
      itemCount: list.length,
    );
  }
}

class _ProductItemWidget extends StatelessWidget {
  final Product product;

  const _ProductItemWidget({
    Key key,
    @required this.product,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 76,
      child: Row(
        children: <Widget>[
          SizedBox(width: 18),
          ClipRRect(
            borderRadius: BorderRadius.circular(3),
            child: CachedNetworkImage(
              imageUrl: product.productImage,
              width: 60,
              height: 60,
              fit: BoxFit.fill,
            ),
          ),
          SizedBox(width: 23),
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '${product.productName}',
                  style: TextStyle(fontSize: 16),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/order/img_params.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                  width: 76,
                  height: 22,
                  child: Text(
                    '产品属性',
                    style: TextStyle(color: Colors.white, fontSize: 14),
                  ),
                )
              ],
            ),
          ),
          Text(
            'x${product.quantity}',
            style: TextStyle(color: Colors.grey, fontSize: 16),
          ),
          SizedBox(width: 30),
        ],
      ),
    );
  }
}

class _OrderBottomWidget extends StatelessWidget {
  final Order order;

  const _OrderBottomWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    int totalQuantity = 0;
    order.orderDetails.forEach((product) {
      totalQuantity += product.quantity;
    });
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.vertical(
          bottom: Radius.circular(10),
        ),
      ),
      height: 60,
      margin: EdgeInsets.only(bottom: 12),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  order.createTime ?? '--',
                  style: TextStyle(color: Colors.grey, fontSize: 13),
                ),
              ),
              Text.rich(
                TextSpan(
                  text: '共$totalQuantity件商品 合计：',
                  style: TextStyle(color: Colors.grey, fontSize: 13),
                  children: [
                    TextSpan(
                      text: '￥',
                      style: TextStyle(fontSize: 8),
                    ),
                    TextSpan(
                      text: '${order.amount}',
                      style: TextStyle(fontSize: 15),
                    )
                  ],
                ),
              ),
            ],
          ),
          _OperationWidget(
            order: order,
          ),
        ],
      ),
    );
  }
}

/// 操作按钮
class _OperationWidget extends StatelessWidget {
  final Order order;

  const _OperationWidget({
    Key key,
    @required this.order,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 店铺订单，就屏蔽操作按钮
    OrderListModel model = Provider.of(context, listen: false);
    if (model.storeId != null) {
      return Container();
    }
    // 用户订单，根据状态显示不同操作
    switch (order.orderStatus) {
      case 'UNPAID':
      case 'PAYING':
        return ChangeNotifierProvider(
          create: (context) => OrderRepayModel(Provider.of(context, listen: false)),
          child: Consumer<OrderRepayModel>(
            builder: (context, model, child) {
              return _OperationButtonWidget(
                title: '继续支付',
                onTap: () {
                  _onRepayClicked(context);
                },
                busy: model.viewState == ViewState.busy,
              );
            },
          ),
        );
      case 'PAID':
        switch (order.deliveryStatus) {
          case 'CONFIRMING':
            return ChangeNotifierProvider(
              create: (context) => OrderConfirmReceiptModel(Provider.of(context, listen: false)),
              child: Consumer<OrderConfirmReceiptModel>(
                builder: (context, model, child) {
                  return _OperationButtonWidget(
                    title: '确认收货',
                    onTap: () {
                      _onReceiptClicked(context);
                    },
                    busy: model.viewState == ViewState.busy,
                  );
                },
              ),
            );
        }
        break;
      case 'CANCELLED':
        return ChangeNotifierProvider(
          create: (context) => OrderDeleteModel(Provider.of(context, listen: false)),
          child: Consumer<OrderDeleteModel>(
            builder: (context, model, child) {
              return _OperationButtonWidget(
                title: '删除订单',
                onTap: () {
                  _onDeleteClicked(context);
                },
                busy: model.viewState == ViewState.busy,
              );
            },
          ),
        );
    }
    return Container();
  }

  /// 继续支付
  void _onRepayClicked(BuildContext context) async {
    OrderRepayModel model = Provider.of(context, listen: false);
    var viewState = await model.orderRepay(order.code, order.payMode);
    switch (viewState) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        showToast('支付完成');
        OrderListModel orderListModel = Provider.of(context, listen: false);
        orderListModel.refreshData();
        break;
    }
  }

  /// 确认收货
  void _onReceiptClicked(BuildContext context) async {
    OrderRepayModel model = Provider.of(context, listen: false);
    var viewState = await model.orderRepay(order.code, order.payMode);
    switch (viewState) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        showToast('确认完成');
        OrderListModel orderListModel = Provider.of(context, listen: false);
        orderListModel.refreshData();
        break;
    }
  }

  /// 删除订单
  void _onDeleteClicked(BuildContext context) async {
    OrderDeleteModel model = Provider.of(context, listen: false);
    var viewState = await model.orderDelete(order.code);
    switch (viewState) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        showToast('删除成功');
        OrderListModel orderListModel = Provider.of(context, listen: false);
        orderListModel.refreshData();
        break;
    }
  }
}

class _OperationButtonWidget extends StatelessWidget {
  final String title;
  final Function onTap;
  final bool busy;

  const _OperationButtonWidget({
    Key key,
    @required this.title,
    @required this.onTap,
    this.busy = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 75,
      height: 20,
      child: busy
          ? RaisedButton(
              onPressed: null,
              child: SizedBox(
                width: 14,
                height: 14,
                child: CircularProgressIndicator(),
              ),
            )
          : RaisedButton(
              onPressed: onTap,
              padding: EdgeInsets.zero,
              child: Text(title),
            ),
    );
  }
}
